import Notify from '@vant/weapp/notify/notify';
const app = getApp()
Page({
  data: {
    click_button: 0,
    phone: '',
    code: '',
    password: '',
    send: true,
    alreadySend: false,
    second: 60,
    checked: false,
    idcards: [],
    idcardFrontImage: '',
    idcardBackImage: '',
    fileToken: '',
    ocrFront: '',
    ocrBack: '',
    roleId: 2,
    isStop: false,
    ocrInfoFront:{
      name: "",
      number_id: "",
      address: "",
      nation: "",//民族
      sex: "",
      birthday: ""
    },
    schoolList: [
      {
          education: "",
          school: "",
          speciality: "",
          time: [],
          diploma: "",
          degree: "",
          stu_card: ""
      }
    ],
    workList: [
      {
        name: "",
        industry: "",
        post: "",
        time: ['', ''],
        start_time: "",
        end_time: "",
        keyword: "",
        keyword_new: "",
        beginTimeShow: false,
        endTimeShow: false
      }
    ],
    minDate: new Date(2010, 0, 1).getTime(),//不要设置范围太大，导致卡
    fields: ['year', 'month', 'day'],
  },

  onShow: function () {
    var that = this;
    that.getOpenid();
    this.getFileToken()
    this.initTestData()
  },
  addWorkList() {
    let work = {
      name: "",
      industry: "",
      post: "",
      time: ['', ''],
      start_time: "",
      end_time: "",
      keyword: "",
      keyword_new: "",
      beginTimeShow: false,
      endTimeShow: false,
    }
    this.data.workList.push(work)
    this.setData({workList: this.data.workList})
    console.log(this.data.workList)
  },
  onBeginPickerChange(e) {
    this.setData({[`workList[${e.currentTarget.dataset.info}].start_time`]: this.formatDate(e.detail.value)})
  },
  onEndPickerChange(e) {
    this.setData({[`workList[${e.currentTarget.dataset.info}].end_time`]: this.formatDate(e.detail.value)})
  },
  onBeginTimeShowDisplay(event) {
    this.setData({[`workList[${event.currentTarget.dataset.info}].beginTimeShow`]: true})
  },
  onBeginTimeShowClose(event) {
    this.setData({[`workList[${event.currentTarget.dataset.info}].beginTimeShow`]: false})
  },
  onBeginTimeShowConfirm(event) {
    this.setData({[`workList[${event.currentTarget.dataset.info}].start_time`]: this.formatDate(event.detail)})
    this.setData({[`workList[${event.currentTarget.dataset.info}].beginTimeShow`]: false})
  },
  onEndTimeShowDisplay(event) {
    console.log("onEndTimeShowDisplay")
    this.setData({[`workList[${event.currentTarget.dataset.info}].endTimeShow`]: true})
  },
  onEndTimeShowClose(event) {
    this.setData({[`workList[${event.currentTarget.dataset.info}].endTimeShow`]: false})
  },
  onEndTimeShowConfirm(event) {
    this.setData({[`workList[${event.currentTarget.dataset.info}].end_time`]: this.formatDate(event.detail)})
    this.setData({[`workList[${event.currentTarget.dataset.info}].endTimeShow`]: false})
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  initTestData() {
    this.setData({code: "425381"})
    this.setData({password: "425381"})
    this.setData({idcardNumber: "123456198108047890"})
  },
  getFileToken() {
    let that = this
    wx.request({
      url: app.globalData.domain + 'uploads/upload_key/',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.setData({
          fileToken: res.data.data.key
        })
      }
    })
  },
  idCardDelete(event) {
    this.setData({
      idcards: []
    })
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    var that = this;
    wx.uploadFile({
      url: app.globalData.domain + 'uploads/?upcheck=' + that.data.fileToken + '&up_type=number_id_img', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      // formData: { user: 'test' },
      success(res) {
        var data = JSON.parse(res.data)
        // 上传完成需要更新 fileList
        let imageInfo = {
          url: app.globalData.domain + "file/" + data.data[0].file_url,
          name: '身份证正面',
          isImage: true,
          deletable: true,
        }
        that.setData({
          idcardFrontImage: imageInfo.url
        })
        let fileList = []
        fileList.push(imageInfo);
        that.setData({
          idcards: fileList
        });
        wx.request({
          url: app.globalData.domain + 'interviewer/ocr_sfz/',
          method: "POST",
          data: {
            idCardSide: 'front',
            url: imageInfo.url
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            if (res.data.response === 'ok') {
              Notify({
                type: 'primary',
                message: '身份证上传成功'
              });
              let ocrInfo = res.data.data;
              that.setData({ocrInfoFront: ocrInfo
              })
              that.setData({
                ocr_front: ocrInfo
              })
            } else {
              Notify({
                type: 'danger',
                message: '身份证识别失败:' + res.data.message
              });
            }
          }
        })
      }
    })
  },
  saveStep1Stop(){
    this.saveStep1(1)
  },
  saveStep1(is_stop) {
    if(is_stop != 1){
      is_stop = 0
      console.log("不是暂存")
    }else{
      console.log("暂存")
    }
    if (!this.data.idcardFrontImage) {
      Notify({
        type: 'danger',
        message: '请上传身份证正面'
      });
      return false
    }
    var post_data = {
      token:  "",
      step_id: 1,
      password1: this.data.password,
      phone: this.data.phone,
      code: this.data.code,
      front: this.data.idcardFrontImage,
      back: this.data.idcardBackImage,
      is_stop: this.data.isStop,
      info_front: JSON.stringify(this.data.ocrInfoFront),
      ocr_info_front: JSON.stringify(this.data.ocrBack),
    }
    var that = this;
    wx.request({
      url: app.globalData.domain + '/interviewer/save/?role_id=' + that.data.roleId,
      method: "POST",
      data: post_data,
      success: function(res){
        if(res.data.response == "ok"){
          app.setToken(res.data.data.token)
          app.setUserId(res.data.data.user_id)
          app.setRole("用户")
          app.setAdminName(that.data.phone)
          app.setSessionTable("yonghu")
        }else {
          Notify({
            type: 'danger',
            message: res.data.message
          });
        }
      }
    })
    // wx.requet("/interviewer/save/?role_id=" + that.role_id, post_data, function (res) {
    //   that.loading_post = false;
    //   if (res.response === 'ok') {
    //     localStorage.setItem("Token", res.data.token);
    //     that.token = res.data.token
    //     if (is_stop) {
    //       that.$message.success("暂存成功");
    //     } else {
    //       that.active++
    //     }
    //     localStorage.setItem("userId", res.data.user_id);
    //     localStorage.setItem("role", '用户');
    //     localStorage.setItem("sessionTable", 'yonghu');
    //     localStorage.setItem("adminName", that.form.phone);
    //     let timer = setTimeout(function () {
    //       window.parent.document.getElementById('iframe').height = 0
    //       let height = window.parent.document.getElementById('iframe').contentDocument.body.scrollHeight + 100
    //       height = window.parent.innerHeight > height ? window.parent.innerHeight : height
    //       window.parent.document.getElementById('iframe').height = height
    //       clearTimeout(timer)
    //     }, 200)
    //   } else {
    //     that.$message.error(res.message);
    //   }
    // })
  },
  checkedTap: function (e) {
    this.setData({
      checked: !this.data.checked
    })
  },


  xieyi: function (e) {
    wx.showToast({
      title: '《云数用户协议》',
      icon: 'none',
      duration: 2000,
    })
  },

  zhengce: function (e) {
    wx.showToast({
      title: '《云数隐私政策》',
      icon: 'none',
      duration: 2000,
    })
  },

  submit_result: function () {
    var that = this;
    if (that.data.phone == "") {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none',
        duration: 2000,
      })
    } else if (!(/^1(3|4|5|7|8|9)\d{9}$/.test(that.data.phone))) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none',
        duration: 2000,
      })
    } else if (!(that.data.code)) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000,
      })
    } else if (!(that.data.password)) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000,
      })
    } else if (that.data.checked == false) {
      wx.showToast({
        title: '请同意《云数用户协议》和《云数隐私政策》',
        icon: 'none',
        duration: 2000,
      })
    } else {
      this.setData({
        click_button: 1
      })
      wx.request({
        url: app.globalData.domain + 'index/personReg/',
        method: "POST",
        data: {
          phone: that.data.phone,
          code: that.data.code,
          password: that.data.password,
          openid: wx.getStorageSync('openid')
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          if (res.data.code == 0) {
            wx.showToast({
              title: '注册成功！',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  phone: '',
                  code: '',
                  password: '',
                  click_button: 0,
                  send: true,
                  alreadySend: false,
                  second: 60
                })
                setTimeout(() => {
                  wx.navigateTo({
                    url: '/pages/center/login',
                  })
                }, 2000);
              }
            })
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000,
              success: function () {
                //...
              }
            })
          }
        }
      })
    }
  },

  //获取openid
  getOpenid: function () {
    var that = this;
    wx.login({
      success: function (myres) {
        // console.log(myres.code)
        wx.request({
          url: app.globalData.domain + 'index/getOpenid/',
          method: "POST",
          data: {
            code: myres.code,
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            wx.setStorageSync("openid", res.data.data.openid);
          }
        })
      }
    })
  },

  getPhone: function (e) {
    this.setData({
      phone: e.detail.value,
    })
  },
  getCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  getPassword: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  sendMsg: function (options) {
    var that = this;
    if (that.data.phone == "") {
      wx.showToast({
        title: '请填写您的手机号码',
        icon: 'none',
        duration: 2000,
      })
    } else {
      if ((/^1(3|4|5|7|8|9)\d{9}$/.test(that.data.phone))) {
        that.setData({
          alreadySend: true,
          send: false
        })
        that.timer();
        wx.request({
          url: app.globalData.domain + 'index/sendCode/',
          method: "POST",
          data: {
            phone: that.data.phone,
            openid: wx.getStorageSync('openid')
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            if (res.data.code == -1) {
              wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'success',
                duration: 2000
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '请填写正确的手机号码',
          icon: 'error',
          duration: 2000,
        })
      }
    }
  },

  timer: function () {
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              alreadySend: false,
              send: true
            })
            resolve(setTimer)
          }
        }, 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },

  goLogin: function () {
    wx.navigateTo({
      url: '/pages/center/login',
    })
  }

})